package com.bookbuf.android.permission;

import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.bookbuf.android.permission.entity.MonitorActivityEntity;
import com.bookbuf.android.permission.entity.PermEntityCompat;

import java.util.Arrays;

/**
 * Created by robert on 16/5/27.
 */
public class PermUtil {

	private static final String TAG = "PermUtil";

	public static <T extends PermEntityCompat> String[] permissions (T[] permEntities) {
		if (permEntities == null) {
			return null;
		} else {
			int length = permEntities.length;
			String[] array = new String[length];
			for (int i = 0; i < length; i++) {
				array[i] = permEntities[i].getPermission ();
			}
			return array;
		}
	}

	/*发起请求的 requestCode 应是一次请求的 traceId 而不是注册的回调接收者*/
	public static <T extends PermEntityCompat> void request (MonitorActivityEntity t, T[] permEntities) {
		int traceId = PermMonitor.Box.filter (permEntities);
		if (traceId != -1) {
			Log.d (TAG, "request: 发起请求:" + traceId + "," + Arrays.toString (permissions (permEntities)));
			ActivityCompat.requestPermissions (t.getContainer (), permissions (permEntities), traceId);
		} else {
			throw new IllegalArgumentException ("Box 中未查找到匹配的 traceId");
		}
	}

	public static <T extends PermEntityCompat> boolean check (MonitorActivityEntity t, T[] permEntities) {
		if (permEntities == null) {
			return false;
		}
		boolean bool = true;
		if (t == null || t.getContainer () == null) {
			return false;
		}
		for (String permission : permissions (permEntities)) {
			bool &= ContextCompat.checkSelfPermission (t.getContainer (), permission) == PackageManager.PERMISSION_GRANTED;
		}
		return bool;
	}

	public static <T extends PermEntityCompat> boolean canShowRequestUI (MonitorActivityEntity t, T[] permEntities) {
		if (permEntities == null) {
			return false;
		} else {
			for (String permission : permissions (permEntities)) {
				boolean bool = ActivityCompat.shouldShowRequestPermissionRationale (t.getContainer (), permission);
				if (bool) {
					return true;
				}
			}
			return false;
		}
	}
}
